package com.sso.server.util;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

/**
 * 阿里发短信
 */
public class AliSmsUtil {

    private static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }


    /**
     * 发送短信
     * @param accessKeyId
     * @param accessKeySecret
     * @param signName
     * @param templateCode
     * @param phoneNumber
     * @param templateParam 格式： {\"code\":\"1234\"}
     * @throws Exception
     */
    public static String send(String accessKeyId,String accessKeySecret,String signName,String templateCode,String phoneNumber,String templateParam) throws Exception {

        Client client = AliSmsUtil.createClient(accessKeyId, accessKeySecret);
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(signName)
                .setTemplateCode(templateCode)
                .setPhoneNumbers(phoneNumber)
                .setTemplateParam(templateParam);
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            SendSmsResponse resp= client.sendSmsWithOptions(sendSmsRequest, runtime);
            return resp.getBody().getMessage();
        }catch (Exception _error) {
            _error.printStackTrace();
            return _error.getMessage();
        }
    }
}
